<template>
  <div class="list-classify">
    <BasicTree
      title="表单类型配置" treeWrapperClassName="h-[calc(100%-35px)] overflow-auto" :clickRowToExpand="false"
      :treeHeaderAction="treeHeaderAction" :treeData="treeData" :actionList="actionList"
      :fieldNames="{ key: 'groupId', title: 'groupName' }" >
      <template #onlyTitle="data">
        <div>
          {{ data.groupName }}{{data.countLevel ? `(计算级别:${data.countLevel})` : ''}}{{ data.description ? `(${data.description})` : '' }}
        </div>
        
      </template>
    </BasicTree>
    <BasicModal @register="handleRegister" @ok="handleSuccess" :title="getTitle" >
      <BasicForm @register="registerForm"  >
        <template #sumary="scope">
          <div>
            {{ scope.model.functionDesc }}
            <Button type="primary" @click="handleOpenSumaryModal(scope.model)">编辑公式</Button>
          </div>
        </template>
      </BasicForm>
    </BasicModal> 
    <SumaryModal @register="registerSumaryModal" @success="handleConfirmSumary"></SumaryModal>
  </div>
</template>

<script lang="ts" setup>
import { ref, h, createVNode, nextTick, computed, type Ref, unref } from 'vue'
import { BasicTree, ContextMenuItem, TreeItem } from '@/components/Tree';
import { BasicModal } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { TreeActionItem } from '@/components/Tree/index';
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined
} from '@ant-design/icons-vue';
import { message, Modal, Button } from 'ant-design-vue';
import SumaryModal from './SumaryModal.vue';
import { useModal, useModalInner } from '@/components/Modal/index';
import { getlistClassifyTree, addorupdateListClassify, getlistClassifyTreeDetail, delListClassify } from '@/api/collection/classify'
import { listClassifyTypeFormSchema } from './data'
type ActionType = 'add' | 'edit'
let actionType: Ref<ActionType> = ref('add')
let currentTreeData = ref({})
const [registerTypeModal, { openModal: openClassifyTypeModal, closeModal }] = useModal()
const [registerModal, { setModalProps }] = useModalInner(async (data) => {
  resetFields()
  actionType.value = data.actionType
  currentTreeData.value = data.ret
  setModalProps({ confirmLoading: true })
  if (unref(actionType) == 'edit') {
    const params = {
      groupId: data.ret.groupId
    }
    let res = await getlistClassifyTreeDetail(params)
    console.log(res, 'res')
    setFieldsValue({
      ...res
    })
  }
  setModalProps({confirmLoading: false})
})
const [registerSumaryModal, {openModal: openSumaryModal, closeModal: closeSumaryModal}] = useModal()

const handleRegister = (instance, uuid) => {
  registerTypeModal(instance, uuid)
  registerModal(instance, uuid)
}
const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: listClassifyTypeFormSchema,
  showActionButtonGroup: false,
})

const treeHeaderAction = () => {
  openClassifyTypeModal(true, {
    isUpdate: false,
  });
};
const actionList: TreeActionItem[] = [
  {
    render: (node) => {
      return h(PlusOutlined, {
        class: 'ml-2',
        onClick: (e) => {
          e.stopPropagation()
          handleAddChildren(node)
        },
      });
    },
  },
  {
    render: (node) => {
      return h(EditOutlined, {
        class: 'ml-2',
        onClick: (e) => {
          e.stopPropagation()
          handleEdit(node)
        },
      });
    },
  },
  {
    render: (node) => {
      return h(DeleteOutlined, {
        class: 'ml-2',
        onClick: (e) => {
          e.stopPropagation()
          showConfirm(node)
        },
      });
    },
  },
];
const treeData = ref<TreeItem[]>([]);
const showConfirm = (node) => {
  Modal.confirm({
    title: '确认删除该表单类型?',
    icon: createVNode(DeleteOutlined),
    onOk() {
      handleDelete(node);
    },
    onCancel() { },
  });
};

const handleDelete = async (node) => {
  await delListClassify({groupId: node.groupId})
  // await deleteClassify({ classifyId: node.classifyId })
  fetch()
  message.success('删除成功')
}

const getTitle = computed(() => (!unref(actionType) ? '新增表单类型' : '编辑表单类型'))
async function handleEdit(record: Recordable) {
  openClassifyTypeModal(true, {
    actionType: 'edit',
    ret: record
  }, false)
}

async function handleAddChildren(record: Recordable) {
  openClassifyTypeModal(true, {
    actionType: 'add',
    ret: record
  }, true)
}

const handleSuccess = async () => {
  
  const values = await validate()
  console.log(values)
  let params
  if (actionType.value === 'add') {
    params = {
      ...values,
      parentGroupId: currentTreeData.value.groupId,
    }
  } else {
    params = {
      ...values
    }
  }
  console.log(params)
  setModalProps({confirmLoading: true})
  await addorupdateListClassify(params)
  fetch()
  closeModal()
  message.success(actionType.value === 'add' ? '添加成功' : '修改成功')
  setModalProps({confirmLoading: false})
}
const handleConfirmSumary = async (formValue) => {
  console.log(formValue)
  await setFieldsValue({
    ...formValue
  })
  closeSumaryModal()
}
const handleOpenSumaryModal = (values) => {
  openSumaryModal(true, {
    ...values
  })
}
async function fetch() {
  const res = await getlistClassifyTree()
  console.log(res)
  treeData.value = res
}

fetch()
</script>

<style lang="less" scoped>
.list-classify{
  overflow: auto;
  height: 100vh;
}
</style>